// pages/detail/detail.js
import { request } from '../../utils/http'
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        shopId: 1,
        // picDomain: config.picDomain,
        indicatorDots: true,
        indicatorColor: '#f2f2f2',
        indicatorActiveColor: '#eb2444',
        autoplay: true,
        interval: 3000,
        duration: 1000,
        prodNum: 1,
        totalCartNum: 0,
        pic: "",
        imgs: '',
        prodName: '',
        price: 0,
        content: '',
        prodId: 0,
        brief: '',
        skuId: 0,
        popupShow: false,
        // 是否获取过用户领取过的优惠券id
        loadCouponIds: false,
        skuShow: false,
        commentShow: false,
        couponList: [],
        skuList: [],
        skuGroup: {},
        findSku: true,
        defaultSku: undefined,
        selectedProp: [],
        selectedPropObj: {},
        propKeys: [],
        allProperties: [],
        prodCommData: {},
        prodCommPage: {
            current: 0,
            pages: 0,
            records: []
        },
        littleCommPage: [],
        evaluate: -1,
        isCollection: false,
    },

    // // 获取商品信息
    getProdInfo() {
        request({
            url: '/prod/prodInfo',
            data: {
                prodId: this.data.prodId,
            },
        }).then(littleCommPage => {
            var imgStrs = littleCommPage.imgs;
            var imgs = imgStrs.split(",");
            // var content = util.formatHtml(littleCommPage.content);
            this.setData({
                imgs: imgs,
                content: littleCommPage.content,
                price: littleCommPage.price,
                prodName: littleCommPage.prodName,
                prodId: littleCommPage.prodId,
                brief: littleCommPage.brief,
                skuList: littleCommPage.skuList,
                pic: littleCommPage.pic
            })
            this.groupSkuProp();
        })
    },
    //评价弹窗
    showComment() {
        this.setData({
            commentShow: true
        });
    },
    //关闭弹窗
    closePopup() {
        this.setData({
            popupShow: false,
            skuShow: false,
            commentShow: false
        });
    },
    //购物车弹窗
    showSku() {
        this.setData({
            skuShow: true
        });
    },
    //加入购物车
    addToCart(event) {
        if (!this.data.findSku) {
            return;
        }
        var ths = this;
        request({
            url: '/p/shopCart/changeItem',
            method: "POST",
            data: {
                basketId: 0,
                count: this.data.prodNum,
                prodId: this.data.prodId,
                shopId: this.data.shopId,
                skuId: this.data.defaultSku.skuId
            },
        }).then(res => {
            
            ths.setData({
                totalCartNum: ths.data.totalCartNum + ths.data.prodNum
            });
            wx.showToast({
                title: "加入购物车成功",
                icon: "none"
            })
        })
    },
    //收藏
    addOrCannelCollection() {
        request({
            url: "/p/user/collection/addOrCancel",
            method: "POST",
            data: this.data.prodId,
        }).then(res => {
            this.setData({
                isCollection: !this.data.isCollection
            })
        })
    },
    //跳转首页
    toHomePage() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    /**
  * 跳转到购物车
  */
    toCartPage() {
       wx.switchTab({
            url: '/pages/index/index',
        })
    },
    //立即购买
    buyNow() {
        if (!this.data.findSku) {
            return;
        }
        wx.setStorageSync("orderItem", JSON.stringify({
            prodId: this.data.prodId,
            skuId: this.data.defaultSku.skuId,
            prodCount: this.data.prodNum,
            shopId: this.data.shopId
        }));
        wx.navigateTo({
            url: '/pages/baybuy/baybuy?orderEntry=1',
        })

    },
    /**
 * 减数量
 */
    onCountMinus() {
        var prodNum = this.data.prodNum;
        if (prodNum > 1) {
            this.setData({
                prodNum: prodNum - 1
            });
        }
    },

    /**
     * 加数量
     */
    onCountPlus() {
        var prodNum = this.data.prodNum;
        if (prodNum < 1000) {
            this.setData({
                prodNum: prodNum + 1
            });
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        
        this.setData({
            prodId: options.prodid
        })
        this.getProdInfo()
    },
    /**
      * 根据skuList进行数据组装
      */
    groupSkuProp() {
        var skuList = this.data.skuList;
        
        //当后台返回只有一个SKU时，且SKU属性值为空时，即该商品没有规格选项，该SKU直接作为默认选中SKU
        if (skuList.length == 1 && skuList[0].properties == "") {
            this.setData({
                defaultSku: skuList[0]
            });
            return;
        }

        var skuGroup = {};//所有的规格名(包含规格名下的规格值集合）对象，如 {"颜色"：["金色","银色"],"内存"：["64G","256G"]}
        var allProperties = [];//所有SKU的属性值集合，如 ["颜色:金色;内存:64GB","颜色:银色;内存:64GB"]
        var propKeys = [];//所有的规格名集合，如 ["颜色","内存"]

        for (var i = 0; i < skuList.length; i++) {

            //找到和商品价格一样的那个SKU，作为默认选中的SKU
            var defaultSku = this.data.defaultSku;
            var isDefault = false;
            if (!defaultSku && skuList[i].price == this.data.price) {
                defaultSku = skuList[i];
                isDefault = true;
                this.setData({
                    defaultSku: defaultSku
                });
            }

            var properties = skuList[i].properties; //如：版本:公开版;颜色:金色;内存:64GB
            allProperties.push(properties);
            var propList = properties.split(";"); // 如：["版本:公开版","颜色:金色","内存:64GB"]

            var selectedPropObj = this.data.selectedPropObj;
            for (var j = 0; j < propList.length; j++) {

                var propval = propList[j].split(":"); //如 ["版本","公开版"]
                var props = skuGroup[propval[0]]; //先取出 规格名 对应的规格值数组

                //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
                if (isDefault) {
                    propKeys.push(propval[0]);
                    selectedPropObj[propval[0]] = propval[1];
                }

                if (props == undefined) {
                    props = []; //假设还没有版本，新建个新的空数组
                    props.push(propval[1]); //把 "公开版" 放进空数组
                } else {
                    if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
                        props.push(propval[1]); //把 "公开版" 放进数组
                    }
                }
                skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
            }
            this.setData({
                selectedPropObj: selectedPropObj,
                propKeys: propKeys
            });
        }
        this.parseSelectedObjToVals();
        this.setData({
            skuGroup: skuGroup,
            allProperties: allProperties
        });
    },
    //将已选的 {key:val,key2:val2}转换成 [val,val2]
    parseSelectedObjToVals() {
        var selectedPropObj = this.data.selectedPropObj;
        var selectedProperties = "";
        var selectedProp = [];
        for (var key in selectedPropObj) {
            selectedProp.push(selectedPropObj[key]);
            selectedProperties += key + ":" + selectedPropObj[key] + ";";
        }
        selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
        this.setData({
            selectedProp: selectedProp
        });

        var findSku = false;
        for (var i = 0; i < this.data.skuList.length; i++) {
            if (this.data.skuList[i].properties == selectedProperties) {
                findSku = true;
                this.setData({
                    defaultSku: this.data.skuList[i],
                });
                break;
            }
        }
        this.setData({
            findSku: findSku
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            totalCartNum: app.globalData.totalCartCount
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})